<template>
  <dialog-editor ref="dialog" :print-func='printHandle' :top='top'></dialog-editor>
</template>

<script>
import DialogEditor from '@/components/DialogEditor'
import dialogMixins from '@/utils/commonDialogMixins'
import {mRequest} from '@/utils/request'

export default {
  mixins: [dialogMixins],
  components: {DialogEditor},
  data() {
    return {
      dataFormConfig: {
        id: {
          hidden: true
        },
        clientId: {
          type: 'list',
          list: [],
          label: '客户名',
          filterable: true,
          clearable: true,
          showInMultiMode: true,
          placeholder: '请输入客户',
          selectCallback: this.clientIdSelectCallback
        },
        orderDetailId: {
          label: '订单',
          type: 'list',
          list: [],
          placeholder: '请输入订单',
          filterable: true,
          selectCallback: this.orderSelectCallback
        },
        productId: {
          label: '产品',
          type: 'list',
          list: [],
          //   disabled: true,
          filterable: true,
          clearable: true,
          placeholder: '请输入产品',
          selectCallback: this.productSelectCallback
        },
        productWeight: {
          label: '克数',
          type: 'number',
          max: 1000,
          default: 0
        },
        outTime: {
          label: '出库时间',
          type: 'date',
          showInMultiMode: true,
          placeholder: '请选择出库时间'
        },
        boxSupplyWay: {
          label: '纸箱供应方式',
          type: 'radio',
          radioBorder: true,
          radioList: [
            {text: '纸箱', label: 0},
            {text: '托盘', label: 1},
            {text: '自供', label: 2}
          ],
          default: 0
        },
        trayInfoId: {
          label: '托盘',
          type: 'list',
          placeholder: '请选择托盘',
          list: [],
          reply: () => this.R.equals(1, this.dataForm['boxSupplyWay'])
        },
        trayLayerNumber: {
          label: '托盘层数',
          type: 'number',
          default: 0,
          reply: () => this.R.equals(1, this.dataForm['boxSupplyWay']),
          selectCallback: this.numberChanged

        },
        trayEachZhiNumber: {
          label: '托盘每层只数',
          type: 'number',
          default: 0,
          reply: () => this.R.equals(1, this.dataForm['boxSupplyWay']),
          selectCallback: this.numberChanged
        },
        trayNumber: {
          label: '托盘数量',
          type: 'number',
          max: 10000,
          default: 0,
          reply: () => this.R.equals(1, this.dataForm['boxSupplyWay']),
          selectCallback: this.numberChanged
        },
        boxId: {
          label: '纸箱',
          type: 'list',
          placeholder: '请选择纸箱',
          list: [],
          reply: () => this.R.equals(0, this.dataForm['boxSupplyWay'])
        },
        boxZhiNumber: {
          label: '箱只',
          type: 'number',
          reply: () => !this.R.equals(1, this.dataForm['boxSupplyWay']),
          selectCallback: this.numberChanged
        },
        boxNumber: {
          label: '箱数',
          type: 'number',
          max: 10000,
          default: 0,
          reply: () => !this.R.equals(1, this.dataForm['boxSupplyWay']),
          selectCallback: this.numberChanged
        },
        scrapNumber: {
          label: '零头',
          type: 'number',
          max: 100000,
          default: 0,
          selectCallback: this.numberChanged
        },

        realSaleNumber: {
          label: '出库数量',
          type: 'number',
          max: 1000000
        },

        weightCount: {
          label: '总克数',
          disabled: true
        },
        remark: {
          label: '备注',
          inputType: 'textarea',
          placeholder: '请输入备注'
        },
        status: {
          label: '状态',
          type: 'switch',
          activeValue: 1,
          inactiveValue: 0,
          default: 1
        }
      },
      orderListFilterByClientId: [],
      orderList: [],
      top: '7vh',
      multiAddProduct: false
    }
  },
  methods: {
    printHandle(params) {
      this.$vBus.$emit('SHOW_PRINT_DIALOG', (win) => {
        const tmpDocument = this.R.prop('document', win)
        const content = tmpDocument.querySelector('#content')
        const {clientId, tableData} = params

        const outTime = this.R.propOr('', 'outTime', params)
        const tickerNo = this.R.propOr('', 'tickerNo', params)

        if (this.R.isNil(tmpDocument) || this.R.isNil(content) || !(tableData instanceof Array) || tableData.length < 0) {
          tmpDocument.body.innerHTML = '信息不全'
          return
        }
        const addTd = (tr, str) => {
          const td = tmpDocument.createElement('td')

          td.innerText = str
          tr.appendChild(td)
        }

        tmpDocument.querySelector('#time').innerHTML = outTime.toString().substr(0, 11)
        tmpDocument.querySelector('#tickerNo').innerHTML = tickerNo.toString()

        content.innerHTML = ''

        const client = this.R.find(this.R.propEq('id', clientId), this.dataFormConfig.clientId.list)
        const clientName = client.name

        tableData.forEach(row => {
          const {
            productId,
            productWeight,
            boxSupplyWay,
            boxNumber,
            boxZhiNumber,
            trayNumber,
            trayEachZhiNumber,
            trayLayerNumber,
            weightCount,
            realSaleNumber,
            remark
          } = row
          const product = this.R.find(this.R.propEq('id', productId), this.dataFormConfig.productId.list)

          const productName = product.name
          const boxSupplyWayName = boxSupplyWay === 0 ? '纸箱' : boxSupplyWay === 1 ? '托盘' : '自供'

          const tr = tmpDocument.createElement('tr')

          addTd(tr, clientName)
          // addTd(tr, orderName)
          addTd(tr, productName)
          addTd(tr, boxSupplyWayName)
          if (boxSupplyWay === 0) {
            addTd(tr, boxZhiNumber)
            addTd(tr, boxNumber)
          } else if (boxSupplyWay === 1) {
            addTd(tr, trayEachZhiNumber * trayLayerNumber)
            addTd(tr, trayNumber)
          } else {
            addTd(tr, '')
            addTd(tr, '')
          }
          addTd(tr, weightCount)
          addTd(tr, productWeight)
          //addTd(tr, saleNumber)
          addTd(tr, realSaleNumber)
          //    addTd(tr, outTime)
          addTd(tr, remark)
          content.appendChild(tr)
        })

      }, true)
    },
    productSelectHandle(productId, cb) {
      if (this.R.isNil(productId) || this.R.isEmpty(productId)) {
        return
      }
      mRequest('productApi/productInfoInfo', {id: productId}, ({data}) => {
        if (!(cb instanceof Function)) {
          return
        }
        return cb(data)
      })
    },
    orderSelectHandle(orderId, cb) {
      if (this.R.isNil(orderId) || this.R.isEmpty(orderId)) {
        return
      }
      mRequest('orderApi/orderDetailInfo', {id: orderId}, ({data}) => {
        if (!(cb instanceof Function)) {
          return
        }
        return cb(data)
      })
    },
    orderSelectCallback() {
      this.orderSelectHandle(this.dataForm.orderDetailId, (data) => {
        this.dataForm['productId'] = this.R.pathOr(0, ['orderDetail', 'productId'], data)
        this.dataForm['productWeight'] = this.R.pathOr(0, ['orderDetail', 'productWeight'], data)
        this.dataForm['boxSupplyWay'] = this.R.pathOr(0, ['orderDetail', 'boxSupplyWay'], data)
        this.dataForm['boxZhiNumber'] = this.R.pathOr(0, ['orderDetail', 'boxZhiNumber'], data)
        //TODO 加一个入库数量的提示

      })
    },
    addNewClientInfo() {
      const cb = (newValue) => {
        this.initClientInfoList()
        this.dataForm.clientId = newValue.id
      }
      this.$parent.openClientInfoDialog(cb)

    },
    allOrderListGet() {
      mRequest('orderApi/getOrderDetailList', {clientId: this.dataForm.clientId}, ({data}) => {
        this.orderList = this.R.propOr([], 'list', data)
      })
    },
    clientIdSelectCallback() {
      if (this.multiAddProduct) {
        mRequest('orderApi/getOrderDetailListBtyClientId', {clientId: this.dataForm.clientId}, ({data}) => {
          this.orderListFilterByClientId = this.R.propOr([], 'list', data)
        })
      }else {
        mRequest('orderApi/getOrderDetailListByClientId', {clientId: this.dataForm.clientId}, ({data}) => {
          this.dataFormConfig['orderDetailId'].list = this.R.propOr([], 'list', data)
        })
      }
    },
    productSelectCallback(value) {
      mRequest('productApi/productInfoInfo', {id: value}, (res) => {
        const productInfo = this.R.path(['data', 'productInfo'], res)
        this.dataForm['productWeight'] = productInfo['productWeight']
      })
    },
    numberChanged() {
      const packType = this.R.propOr(0, 'boxSupplyWay', this.dataForm)
      const productWeight = this.R.propOr(0, 'productWeight', this.dataForm)

      if (packType === 0) {
        const boxNumber = this.R.propOr(0, 'boxNumber', this.dataForm)
        const boxZhiNumber = this.R.propOr(0, 'boxZhiNumber', this.dataForm)
        const scrapNumber = this.R.propOr(0, 'scrapNumber', this.dataForm)

        this.dataForm.realSaleNumber = boxNumber * boxZhiNumber + scrapNumber
      } else if (packType === 1) {
        const trayLayerNumber = this.R.propOr(0, 'trayLayerNumber', this.dataForm)
        const trayEachZhiNumber = this.R.propOr(0, 'trayEachZhiNumber', this.dataForm)
        const trayNumber = this.R.propOr(0, 'trayNumber', this.dataForm)
        const scrapNumber = this.R.propOr(0, 'scrapNumber', this.dataForm)

         this.dataForm.countProductNumber = trayLayerNumber * trayEachZhiNumber * trayNumber + scrapNumber
        this.dataForm.realSaleNumber = trayLayerNumber * trayEachZhiNumber * trayNumber  + scrapNumber
      }
      this.dataForm.weightCount = (this.dataForm.realSaleNumber * productWeight)/100000
    },
    init(id, multiAdd) {
      this.dataForm.id = id || 0
      this.initProductInfoList()
      this.initOrderDetailList()
      this.initClientInfoList('clientId')
      this.initBoxInfoIdList('boxId')
      this.initTrayList()
      this.allOrderListGet()
      this.multiAddProduct = multiAdd
      const props = {
        dataForm: this.dataForm,
        config: this.dataFormConfig,
        dataRule: this.getNeedDataRule('clientId', 'productId', 'productOutNumber', 'outTime', 'tickerNo', 'trayNumber', 'boxNumber', 'status'),
        initApi: 'productApi/productLeaveStorageInfo',
        saveApi: 'productApi/saveProductLeaveStorage',
        updateApi: 'productApi/updateProductLeaveStorage',
        objectName: 'productLeaveStorage'
      }

      const weightChangedHandle = (row) => {
        const {boxSupplyWay} = row
        const productWeight = this.R.propOr(0, 'productWeight', row)
        const scrapNumber = this.R.propOr(0, 'scrapNumber', row)

        if (boxSupplyWay !== 1) {
          const boxZhiNumber = this.R.propOr(0, 'boxZhiNumber', row)
          const boxNumber = this.R.propOr(0, 'boxNumber', row)

          row['realSaleNumber'] = Number(boxZhiNumber * boxNumber)+Number(scrapNumber)
          row['weightCount'] = (row['realSaleNumber'] * productWeight)
        }
        if (boxSupplyWay === 1) {
          const trayEachZhiNumber = this.R.propOr(0, 'trayEachZhiNumber', row)
          const trayLayerNumber = this.R.propOr(0, 'trayLayerNumber', row)
          const trayNumber = this.R.propOr(0, 'trayNumber', row)

          row['realSaleNumber'] = Number(trayEachZhiNumber * trayLayerNumber * trayNumber)+Number(scrapNumber)
          row['weightCount'] = row['realSaleNumber'] * productWeight
        }
      }

      if (multiAdd) {
        props['multiSaveApi'] = 'productApi/multipleSaveProductLeaveStorage'

        props['editTableConfig'] = {
          orderDetailId: {
            title: '订单',
            editRenderName: 'xVueBoxSearch',
            optionsGet: () => {
              const filterData = this.orderListFilterByClientId.map(order => ({label: order.orderNo, value: order.id}))

              if (filterData.length > 0) {
                return filterData
              }
              return this.orderList.map(order => ({label: order.name, value: order.id}))
            },
            valueChangeEvent: (row) => {
              const {orderDetailId} = row

              this.orderSelectHandle(orderDetailId, data => {
                row.productId = this.R.pathOr(0, ['orderDetail', 'productId'], data)
                row.boxZhiNumber=this.R.pathOr(0, ['orderDetail', 'boxZhiNumber'], data)
                this.productSelectHandle(row.productId, subData => {
                  row.productWeight = this.R.pathOr(0, ['productInfo', 'productWeight'], subData)
                })
              })
            }
          },
          productId: {
            title: '产品名称',
            editRenderName: 'xVueBoxSearch',
            optionsGet: () => {
              return this.dataFormConfig.productId.list.map(item => ({label: item.name, value: item.id}))
            },
            valueChangeEvent: (row) => {
              const {productId} = row

              this.productSelectHandle(productId, data => {
                row.productWeight = this.R.pathOr(0, ['productInfo', 'productWeight'], data)
                weightChangedHandle(row)
              })
            }
          },
          customerRequire:{
            title: '规格描述',
          },
          productWeight: {
            title: '克数',
            default: 0,
            valueChangeEvent: (row) => {
              weightChangedHandle(row)
            }
          },
          boxSupplyWay: {
            title: '包装方式',
            type: 'select',
            default: 0,
            optionsGet: () => {
              return [
                {label: '纸箱', value: 0},
                // {label: '托盘', value: 1},
                // {label: '客供', value: 2}
              ]
            },
            valueChangeEvent: (row) => {
              weightChangedHandle(row)
            }
          },
          boxZhiNumber: {
            title: '纸箱只数',
            type: 'number',
            default: 0,
            valueChangeEvent: (row) => {
              weightChangedHandle(row)
            }
          },
          boxNumber: {
            title: '纸箱数量',
            type: 'number',
            default: 0,
            valueChangeEvent: (row) => {
              weightChangedHandle(row)
            }
          },
          // trayEachZhiNumber: {
          //   title: '托盘每层只数',
          //   type: 'number',
          //   default: 0,
          //   valueChangeEvent: (row) => {
          //     weightChangedHandle(row)
          //   }
          // },
          // trayLayerNumber: {
          //   title: '托盘层数',
          //   type: 'number',
          //   default: 0,
          //   valueChangeEvent: (row) => {
          //     weightChangedHandle(row)
          //   }
          // },
          // trayNumber: {
          //   title: '托盘数量',
          //   type: 'number',
          //   default: 0,
          //   valueChangeEvent: (row) => {
          //     weightChangedHandle(row)
          //   }
          // },
          scrapNumber: {
            title: '零头',
            type: 'number',
            default: 0,
            valueChangeEvent: (row) => {
              weightChangedHandle(row)
            }
          },
          weightCount: {
            title: '总克数',
            type: 'number',
            default: 0
          },
          realSaleNumber: {
            title: '实际业务数量',
            type: 'number',
            default: 0
          },
          remark: {
            title: '备注',
            type: 'String'
          }
        }
      }
      this.$refs.dialog.initDialog(props)

      this.$nextTick(() => {
        const dataForm = this.dataForm

        Object.defineProperty(dataForm, 'weightCount', {
          get() {
            return dataForm['realSaleNumber'] * dataForm['productWeight']
          }
        })
      })
    }
  }
}
</script>
